<template>
    <div class="admin-container">
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="设备名称">
            <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="员工">
            <el-select 
              v-model="searchForm.employeeId" 
              placeholder="请选择员工"
              filterable
              clearable
            >
              <el-option
                v-for="emp in employeeList"
                :key="emp.jobNumber"
                :label="emp.name"
                :value="emp.jobNumber"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <el-card class="table-card">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="未处理预警" name="unresolvedWarnings">
            <warning-table 
              :data="unresolvedWarnings" 
              :loading="loading"
              type="unresolved"
              @resolve="handleResolveWarning"
            />
          </el-tab-pane>
          <el-tab-pane label="已处理预警" name="resolvedWarnings">
            <warning-table 
              :data="resolvedWarnings" 
              :loading="loading"
              type="resolved"
            />
          </el-tab-pane>
          <el-tab-pane label="未处理报修" name="unresolvedRepairs">
            <repair-table 
              :data="unresolvedRepairs" 
              :loading="loading"
              type="unresolved"
              @process="handleProcessRepair"
              @resolve="handleResolveRepair"
            />
          </el-tab-pane>
          <el-tab-pane label="已处理报修" name="resolvedRepairs">
            <repair-table 
              :data="resolvedRepairs" 
              :loading="loading"
              type="resolved"
            />
          </el-tab-pane>
        </el-tabs>
  
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.current"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </el-card>
  
      <!-- 解决预警对话框 -->
      <el-dialog v-model="showResolveWarningDialog" title="解决预警" width="500px">
        <el-form :model="resolveWarningForm" label-width="100px">
          <el-form-item label="解决方案">
            <el-input 
              v-model="resolveWarningForm.solution" 
              type="textarea" 
              :rows="4"
              placeholder="请输入解决方案"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showResolveWarningDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmResolveWarning">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 处理报修对话框 -->
      <el-dialog v-model="showProcessRepairDialog" title="处理报修" width="500px">
        <el-form :model="processRepairForm" label-width="100px">
          <el-form-item label="分配技术员">
            <el-select 
              v-model="processRepairForm.technicianId" 
              placeholder="请选择技术员"
              filterable
            >
              <el-option
                v-for="tech in technicianList"
                :key="tech.jobNumber"
                :label="tech.name"
                :value="tech.jobNumber"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理意见">
            <el-input 
              v-model="processRepairForm.comment" 
              type="textarea" 
              :rows="4"
              placeholder="请输入处理意见"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showProcessRepairDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmProcessRepair">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 解决报修对话框 -->
      <el-dialog v-model="showResolveRepairDialog" title="解决报修" width="500px">
        <el-form :model="resolveRepairForm" label-width="100px">
          <el-form-item label="处理结果">
            <el-radio-group v-model="resolveRepairForm.result">
              <el-radio :label="1">维修成功</el-radio>
              <el-radio :label="0">维修失败</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="解决方案">
            <el-input 
              v-model="resolveRepairForm.solution" 
              type="textarea" 
              :rows="4"
              placeholder="请输入详细解决方案"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showResolveRepairDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmResolveRepair">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { 
    getWarnings,
    getRepairs,
    resolveWarning,
    processRepair,
    resolveRepair
  } from '@/api/warningAndRepair'
  import { getEmployeeList} from '@/api/device'
  import WarningTable from '@/components/WarningTable.vue'
  import RepairTable from '@/components/RepairTable.vue'
  
  // 搜索表单
  const searchForm = reactive({
    deviceName: '',
    employeeId: '',
    timeRange: []
  })
  
  // 分页
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })
  
  // 标签页
  const activeTab = ref('unresolvedWarnings')
  
  // 数据
  const unresolvedWarnings = ref([])
  const resolvedWarnings = ref([])
  const unresolvedRepairs = ref([])
  const resolvedRepairs = ref([])
  const loading = ref(false)
  const employeeList = ref([])
  const technicianList = ref([])
  
  // 对话框
  const showResolveWarningDialog = ref(false)
  const showProcessRepairDialog = ref(false)
  const showResolveRepairDialog = ref(false)
  
  // 表单
  const resolveWarningForm = reactive({
    warningId: '',
    solution: ''
  })
  
  const processRepairForm = reactive({
    repairId: '',
    technicianId: undefined,
    comment: ''
  })
  
  const resolveRepairForm = reactive({
    repairId: '',
    result: 1,
    solution: ''
  })
  
  // 获取员工列表
  const fetchEmployeeList = async () => {
    try {
      const res = await getEmployeeList()
      employeeList.value = res.data
    } catch (error) {
      ElMessage.error('获取员工列表失败')
    }
  }
  
  // 获取技术员列表
  const fetchTechnicianList = async () => {
    try {
      const res = await getEmployeeList()
      technicianList.value = res.data
    } catch (error) {
      ElMessage.error('获取技术员列表失败')
    }
  }
  
  // 获取预警数据
  const fetchWarnings = async () => {
    try {
      loading.value = true
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        deviceName: searchForm.deviceName,
        employeeId: searchForm.employeeId,
        startTime: searchForm.timeRange?.[0],
        endTime: searchForm.timeRange?.[1],
        resolved: 0
      }
      
      const unresolvedRes = await getWarnings(params)
      unresolvedWarnings.value = unresolvedRes.data.records
      
      params.resolved = 1
      const resolvedRes = await getWarnings(params)
      resolvedWarnings.value = resolvedRes.data.records
      
      pagination.total = unresolvedRes.data.total + resolvedRes.data.total
    } catch (error) {
      ElMessage.error('获取预警数据失败')
    } finally {
      loading.value = false
    }
  }
  
  // 获取报修数据
  const fetchRepairs = async () => {
    try {
      loading.value = true
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        deviceName: searchForm.deviceName,
        employeeId: searchForm.employeeId,
        startTime: searchForm.timeRange?.[0],
        endTime: searchForm.timeRange?.[1],
        resolved: 0,
      }
      
      const unresolvedRes = await getRepairs(params)
      unresolvedRepairs.value = unresolvedRes.data.records
      
      params.resolved = 1
      const resolvedRes = await getRepairs(params)
      resolvedRepairs.value = resolvedRes.data.records
      
      pagination.total = unresolvedRes.data.total + resolvedRes.data.total
    } catch (error) {
      ElMessage.error('获取报修数据失败')
    } finally {
      loading.value = false
    }
  }
  
  // 标签页切换
  const handleTabChange = () => {
    pagination.current = 1
    if (activeTab.value.includes('Warnings')) {
      fetchWarnings()
    } else {
      fetchRepairs()
    }
  }
  
  // 解决预警
  const handleResolveWarning = (warningId :string) => {
    resolveWarningForm.warningId = warningId
    resolveWarningForm.solution = ''
    showResolveWarningDialog.value = true
  }
  
  const confirmResolveWarning = async () => {
    try {
      await resolveWarning({
        id: resolveWarningForm.warningId,
        solution: resolveWarningForm.solution
      })
      ElMessage.success('预警已解决')
      showResolveWarningDialog.value = false
      fetchWarnings()
    } catch (error) {
      ElMessage.error('解决预警失败')
    }
  }
  
  // 处理报修
  const handleProcessRepair = (repairId: string) => {
    processRepairForm.repairId = repairId
    processRepairForm.technicianId = undefined
    processRepairForm.comment = ''
    showProcessRepairDialog.value = true
  }
  
  const confirmProcessRepair = async () => {
    try {
      await processRepair({
        id: processRepairForm.repairId,
        technicianId: processRepairForm.technicianId,
        comment: processRepairForm.comment
      })
      ElMessage.success('报修已处理')
      showProcessRepairDialog.value = false
      fetchRepairs()
    } catch (error) {
      ElMessage.error('处理报修失败')
    }
  }
  
  // 解决报修
  const handleResolveRepair = (repairId:string) => {
    resolveRepairForm.repairId = repairId
    resolveRepairForm.result = 1
    resolveRepairForm.solution = ''
    showResolveRepairDialog.value = true
  }
  
  const confirmResolveRepair = async () => {
    try {
      await resolveRepair({
        id: resolveRepairForm.repairId,
        result: resolveRepairForm.result,
        solution: resolveRepairForm.solution
      })
      ElMessage.success('报修已解决')
      showResolveRepairDialog.value = false
      fetchRepairs()
    } catch (error) {
      ElMessage.error('解决报修失败')
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    if (activeTab.value.includes('Warnings')) {
      fetchWarnings()
    } else {
      fetchRepairs()
    }
  }
  
  // 重置搜索
  const resetSearch = () => {
    searchForm.deviceName = ''
    searchForm.employeeId = ''
    searchForm.timeRange = []
    pagination.current = 1
    if (activeTab.value.includes('Warnings')) {
      fetchWarnings()
    } else {
      fetchRepairs()
    }
  }
  
  // 分页
  const handleSizeChange = (val: number) => {
    pagination.size = val
    if (activeTab.value.includes('Warnings')) {
      fetchWarnings()
    } else {
      fetchRepairs()
    }
  }
  
  const handleCurrentChange = (val: number) => {
    pagination.current = val
    if (activeTab.value.includes('Warnings')) {
      fetchWarnings()
    } else {
      fetchRepairs()
    }
  }
  
  onMounted(() => {
    fetchEmployeeList()
    fetchTechnicianList()
    fetchWarnings()
  })
  </script>
  
  <style scoped>
  .admin-container {
    padding: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>